package com.yzc.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yzc.execption.ZcException;
import com.yzc.mapper.OrderLogMapper;
import com.yzc.model.entity.log.OrderStatusLog;
import com.yzc.redis.RedisUtil;
import com.yzc.result.ResultCodeEnum;
import com.yzc.service.OrderLogService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import static com.yzc.constant.RedisConstant.CACHE_EXPIRE_TIME;

@Slf4j
@Service
public class OrderLogServiceImpl extends ServiceImpl<OrderLogMapper, OrderStatusLog>
        implements OrderLogService {

    @Autowired
    private OrderLogMapper mapper;
    @Autowired
    private RedisUtil redisUtil;

    @Override
    public Boolean createOrderLog(OrderStatusLog orderLog) {
        int insert = mapper.insert(orderLog);
        if (insert == 0) {
            throw new ZcException(ResultCodeEnum.FAIL.getCode(), "创建订单日志失败");
        }
        return true;
    }

    @Override
    public Boolean getOrderLog(Long orderId) {
        String cacheKey = "order_log:" + orderId;
        Long count = (Long) redisUtil.get(cacheKey);
        if (count != null) {
            log.info("从缓存中获取库存回滚日志，订单ID: {}, 条数: {}", orderId, count);
            return count > 0;
        }

        LambdaQueryWrapper<OrderStatusLog> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(OrderStatusLog::getOrderId, orderId)
                .eq(OrderStatusLog::getRemark, "库存回滚");
        log.info("查询库存回滚日志，订单ID: {}, 查询条件: {}", orderId, queryWrapper);

        count = mapper.selectCount(queryWrapper);
        log.info("查询结果，订单ID: {}, 库存回滚日志条数: {}", orderId, count);

        redisUtil.set(cacheKey, count, CACHE_EXPIRE_TIME);

        return count > 0;
    }
}
